package com.xys.libzxing.zxing.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.zxing.Result;
import com.handpay.framework.ClientEngine;
import com.handpay.framework.HttpEngine;
import com.handpay.framework.LuaTableUtil;
import com.handpay.framework.SecureManager;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.HelpWechatPayActivity;
import com.handpay.zztong.hp.QRCodeReceiptActivity;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.ScanQrCodeActivity;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.config.ZZTConstant;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.protocol.ATProtocolConstant;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.trans.activity.VPOSActivity;
import com.xys.libzxing.zxing.camera.CameraManager;
import com.xys.libzxing.zxing.decode.DecodeThread;
import com.xys.libzxing.zxing.utils.BeepManager;
import com.xys.libzxing.zxing.utils.CaptureActivityHandler;
import com.xys.libzxing.zxing.utils.InactivityTimer;

import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Hashtable;

import se.krka.kahlua.vm.LuaTable;

/**
 * This activity opens the camera and does the actual scanning on a background
 * thread. It draws a viewfinder to help the user place the barcode correctly,
 * shows feedback as the image processing is happening, and then overlays the
 * results when a scan is successful.
 */
public final class CaptureActivity extends ZZTongActivity implements SurfaceHolder.Callback {

    private static final String TAG = CaptureActivity.class.getSimpleName();

    private CameraManager cameraManager;
    private CaptureActivityHandler handler;
    private InactivityTimer inactivityTimer;
    private BeepManager beepManager;

    private SurfaceView scanPreview = null;
    private RelativeLayout scanContainer;
    private RelativeLayout scanCropView;
    private ImageView ben_open_merchant;

    private Rect mCropRect = null;
    private boolean isHasSurface = false;
    //    private int mPayType;
    private static final int tradeType = 4;
    public boolean isOpenWechatPayScan;

    public Handler getHandler() {
        return handler;
    }

    private Double amount;

    public CameraManager getCameraManager() {
        return cameraManager;
    }

    @Override
    protected boolean isShownTopBar() {
        return true;
    }


    @Override
    public void onCreate(Bundle icicle) {
        setContentView(R.layout.activity_capture);
//        mPayType = this.getIntent().getIntExtra(PAYTYPE, 0);
        super.onCreate(icicle);

        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        amount = this.getIntent().getDoubleExtra(VPOSActivity.Transfer_Amount_Key, 0d);
        isOpenWechatPayScan = getIntent().getBooleanExtra("isOpenWechatPayScan", false);
        scanPreview = (SurfaceView) findViewById(R.id.capture_preview);
        scanContainer = (RelativeLayout) findViewById(R.id.capture_container);
        scanCropView = (RelativeLayout) findViewById(R.id.capture_crop_view);
        ImageView scanLine = (ImageView) findViewById(R.id.capture_scan_line);
        TextView txt_paycount = (TextView) findViewById(R.id.txt_paycount);
//        String amountStr = String.format("¥%s", CommonUtils.getFromatMoney(amount));
        String amountStr = String.format("¥%s", CommonUtils.formatMoneyWithSplite(amount/100));
//        SpannableString msp = new SpannableString("¥" + CommonUtils.formatMoneyWithSplite(Double.parseDouble(temp_money)));

        SpannableStringBuilder ssb = new SpannableStringBuilder(amountStr);
        ssb.setSpan(new RelativeSizeSpan(1.5f), 1, ssb.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        txt_paycount.setText(ssb);
        TextView txt_webpay_tip = (TextView) findViewById(R.id.txt_webpay_tip);
        ben_open_merchant = (ImageView) findViewById(R.id.btn_opean_merchant);
//        if (mPayType == ReceivablesFragment.PAY_TYPE_ALIPAY) {
//            txt_webpay_tip.setText(R.string.alipay_scanner_tip);
//            ben_open_merchant.setVisibility(View.GONE);
//        } else if (mPayType == ReceivablesFragment.PAY_TYPE_WECHATPAY) {
//            txt_webpay_tip.setText(R.string.weipay_scanner_tip);
//            if (isOpenWechatPayScan) {
//                ben_open_merchant.setVisibility(View.VISIBLE);
//            } else {
//                ben_open_merchant.setVisibility(View.GONE);
//            }
////            getTransferSwitch();
//        }
        ben_open_merchant.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goToScanQrCodeActivity();
            }
        });
        inactivityTimer = new InactivityTimer(this);
        beepManager = new BeepManager(this);

        TranslateAnimation animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.9f);
        animation.setDuration(3000);
        animation.setRepeatCount(-1);
        animation.setRepeatMode(Animation.RESTART);
        scanLine.startAnimation(animation);
    }

    /***
     * 获取微信正扫开关是否打开
     */
    @Deprecated
    private void getTransferSwitch() {
        Hashtable<String, String> params = new Hashtable<>();
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
        params.put("tradeType", tradeType + "");
        params.put("clientVersion", "v" + ClientEngine.VERSION);
        doPost(this, ZZTongActivity.Do_QrCodeTransferSwitch, params, true);
    }

    /***
     * 获取商户二维码
     *
     * @deprecated 此方法过时，现在由客户端自己生成商户二维码
     */
    @Deprecated
    private void getTransferQrCode() {
        Hashtable<String, String> params = new Hashtable<>();
        params.put("amount", SecureManager.getInstance().des(BigDecimal.valueOf(amount).toPlainString(), 1, null));
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
        params.put("tradeType", tradeType + "");
        params.put("clientVersion", "v" + ClientEngine.VERSION);
        Double latitude = (Double) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_LATITUDE, 0d);
        Double longtitude = (Double) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_LONGTITUDE, 0d);
        String address = (String) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_ADDRESS);
        params.put(BaseProtocolKey.KEY_LOCATION, latitude.toString() + "," + longtitude.toString());
        params.put(BaseProtocolKey.KEY_ADDRESS, address);
        doPost(true, this, ZZTongActivity.Do_QrCodeTransfer, params, true, "处理中...", 0);
    }

    /***
     * 跳转到二维码正扫界面
     */
    public void goToScanQrCodeActivity() {
        Intent intent = new Intent();
        intent.putExtra(VPOSActivity.Transfer_Amount_Key, amount);
        intent.putExtra("isFromReceivable", true);
        intent.setClass(CaptureActivity.this, QRCodeReceiptActivity.class);
        startActivity(intent);
        finish();
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }

    @Override
    protected void onResume() {
        super.onResume();

        // CameraManager must be initialized here, not in onCreate(). This is
        // necessary because we don't
        // want to open the camera driver and measure the screen size if we're
        // going to show the help on
        // first launch. That led to bugs where the scanning rectangle was the
        // wrong size and partially
        // off screen.
        cameraManager = new CameraManager(getApplication());

        handler = null;

        if (isHasSurface) {
            // The activity was paused but not stopped, so the surface still
            // exists. Therefore
            // surfaceCreated() won't be called, so init the camera here.
            initCamera(scanPreview.getHolder());
        } else {
            // Install the callback and wait for surfaceCreated() to init the
            // camera.
            scanPreview.getHolder().addCallback(this);
        }

        inactivityTimer.onResume();
    }

    @Override
    protected void onPause() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        inactivityTimer.onPause();
        beepManager.close();
        cameraManager.closeDriver();
        if (!isHasSurface) {
            scanPreview.getHolder().removeCallback(this);
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        cancelVolleyRequest(ZZTongActivity.Do_QrCodeTransfer);
        super.onDestroy();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (holder == null) {
            Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!");
        }
        if (!isHasSurface) {
            isHasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isHasSurface = false;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    /**
     * A valid barcode has been found, so give an indication of success and show
     * the results.
     *
     * @param rawResult The contents of the barcode.
     * @param bundle    The extras
     */
    public void handleDecode(Result rawResult, Bundle bundle) {
        inactivityTimer.onActivity();
        beepManager.playBeepSoundAndVibrate();

        Intent resultIntent = new Intent();
        bundle.putInt("width", mCropRect.width());
        bundle.putInt("height", mCropRect.height());
        bundle.putString("result", rawResult.getText());
        resultIntent.putExtras(bundle);
        HPLog.d("tag-handleDecode", "close");
        this.setResult(RESULT_OK, resultIntent);
        CaptureActivity.this.finish();
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }
        if (cameraManager.isOpen()) {
            Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?");
            return;
        }
        try {
            cameraManager.openDriver(surfaceHolder);
            // Creating the handler starts the preview, which can also throw a
            // RuntimeException.
            if (handler == null) {
                handler = new CaptureActivityHandler(this, cameraManager, DecodeThread.ALL_MODE);
            }

            initCrop();
        } catch (IOException ioe) {
            Log.w(TAG, ioe);
            displayFrameworkBugMessageAndExit();
        } catch (RuntimeException e) {
            // Barcode Scanner has seen crashes in the wild of this variety:
            // java.?lang.?RuntimeException: Fail to connect to camera service
            Log.w(TAG, "Unexpected error initializing camera", e);
            displayFrameworkBugMessageAndExit();
        }
    }

    private void displayFrameworkBugMessageAndExit() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.app_name));
        builder.setMessage("Camera error");
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }

        });
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        });
        builder.show();
    }

    public void restartPreviewAfterDelay(long delayMS) {
        if (handler != null) {
            handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
        }
    }

    public Rect getCropRect() {
        return mCropRect;
    }

    /**
     * 初始化识别区域
     */
    private void initCrop() {
        int cameraWidth = cameraManager.getCameraResolution().y;
        int cameraHeight = cameraManager.getCameraResolution().x;

        /** 宽高*/
        int[] location = new int[2];
        scanCropView.getLocationInWindow(location);

        int cropLeft = location[0];
        int cropTop = location[1] - getStatusBarHeight();

        int cropWidth = scanCropView.getWidth();
        int cropHeight = scanCropView.getHeight();

        /** xml框框区域 */
        int containerWidth = scanContainer.getWidth();
        int containerHeight = scanContainer.getHeight();

        int x = cropLeft * cameraWidth / containerWidth;
        int y = cropTop * cameraHeight / containerHeight;

        int width = cropWidth * cameraWidth / containerWidth;
        int height = cropHeight * cameraHeight / containerHeight;

        mCropRect = new Rect(x, y, width + x, height + y);
    }

    private int getStatusBarHeight() {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public boolean netResponse(String action, Hashtable<String, Object> resp, boolean showAlert) {
        closeProgressDialog();
        if (super.netResponse(action, resp, showAlert)) return true;
        if (action.equals(ZZTongActivity.Do_QrCodeTransferSwitch)) {
            byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
            LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
            Double isOpen = (Double) luaTable.rawget("isOpen");
            HPLog.i(HPLog.SSX_TAG, "微信正扫开关是否打开：" + isOpen);
            if (1 == isOpen.intValue()) {
                ben_open_merchant.setVisibility(View.VISIBLE);
            } else {
                ben_open_merchant.setVisibility(View.GONE);
            }
        } else if (action.equals(ZZTongActivity.Do_QrCodeTransfer)) {
            byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
            LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
            String qrCodeUrl = luaTable.rawget("qrCodeUrl").toString();
            HPLog.i(HPLog.SSX_TAG, "before Secure qrCodeUrl:" + qrCodeUrl);
            String mQrCodeUrl = SecureManager.getInstance().des(qrCodeUrl, 0, null);
            HPLog.i(HPLog.SSX_TAG, "after Secure mQrCodeUrl:" + mQrCodeUrl);
            String orderNo = luaTable.rawget("orderNo").toString();
            String token = luaTable.rawget("token").toString();
            String payOrderID = luaTable.rawget("payOrderID").toString();
            Intent intent = new Intent();
            intent.putExtra("mQrCodeUrl", mQrCodeUrl);
            intent.putExtra("mOrderNo", orderNo);
            intent.putExtra("amount", amount);
            intent.putExtra("tradeType", tradeType);
            intent.putExtra("isOpenWechatPayScan", isOpenWechatPayScan);
            intent.putExtra("token", token);
            intent.putExtra("payOrderID", payOrderID);
            intent.setClass(CaptureActivity.this, ScanQrCodeActivity.class);
            startActivity(intent);
            finish();
        }
        return true;
    }

    @Override
    public ActionBar getActivityActionBar() {
        ImageButton imageButton = new ImageButton(this);
        imageButton.setBackgroundResource(R.drawable.help);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.rightMargin = 20;
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("type", ZZTConstant.WETCHAT_CUSTOMER);
                intent.setClass(CaptureActivity.this, HelpWechatPayActivity.class);
                startActivity(intent);
            }
        });
//        if (mPayType == ReceivablesFragment.PAY_TYPE_ALIPAY) {
        return new ActionBar(this.getString(R.string.capture_title_customer), true);
//        } else {
//        return new ActionBar(this.getString(R.string.capture_title_customer), true, imageButton, layoutParams);
//        }
    }
}